import { MiddlewareHandlerContext } from "$fresh/server.ts";
import { checkIsAdmin } from "../utils/auth.ts";

export interface AdminState {
  isAdmin: boolean;
  adminUsername?: string;
  adminNickname?: string;
  adminUserId?: number;
  adminAvatarUrl?: string | null;
}

// 一个简单的日志中间件，记录每个请求
function logRequest(req: Request) {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  // 记录Cookie
  const cookies = req.headers.get('cookie');
  if (cookies) {
    console.log(`请求Cookie: ${cookies}`);
  } else {
    console.log('请求中没有Cookie');
  }
}

export async function handler(
  req: Request,
  ctx: MiddlewareHandlerContext<AdminState>,
) {
  logRequest(req);
  console.log("中间件处理请求:", req.url);
  // 初始化状态
  ctx.state.isAdmin = false;
  ctx.state.adminUsername = undefined;
  ctx.state.adminNickname = undefined;
  ctx.state.adminUserId = undefined;
  ctx.state.adminAvatarUrl = null;

  // 检查是否为管理员并更新状态
  const isAdmin = await checkIsAdmin(req, ctx);
  ctx.state.isAdmin = isAdmin; // 确保状态被正确设置
  
  console.log("中间件设置的管理员状态:", {
    isAdmin: ctx.state.isAdmin,
    username: ctx.state.adminUsername,
    nickname: ctx.state.adminNickname
  });
  
  const resp = await ctx.next();

  // 如果响应包含任何Set-Cookie头，记录它们
  const headers = resp.headers;
  if (headers.has('set-cookie')) {
    // 在较新的Web标准中，Headers对象没有getAll方法
    // 可以使用Headers.getSetCookie()方法 (如果支持) 或者其他方式获取cookie
    try {
      // 尝试使用现代API
      if (typeof headers.getSetCookie === 'function') {
        const setCookies = headers.getSetCookie();
        console.log('响应设置Cookie:', setCookies);
      } else {
        // 回退方案：获取单个cookie值并记录
        const setCookie = headers.get('set-cookie');
        console.log('响应设置Cookie:', setCookie);
      }
    } catch (e) {
      console.error('获取set-cookie头时出错:', e);
    }
  }
  
  return resp;
} 